#!/usr/bin/env python
# coding=utf-8
# 左菜单

import wsgiref.handlers
from google.appengine.ext import webapp
from google.appengine.api import users
from google.appengine.ext.webapp import util
import common

class LeftHandler(webapp.RequestHandler):
	def get(self):
		user = users.get_current_user()
		if user:
			if users.is_current_user_admin():
				self.response.headers["Content-Type"] = "text/html; charset=utf-8"
				self.response.out.write("""<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Menu - Beikx Cron</title>
    <link href="css/style.css" type="text/css" rel="stylesheet" />
    <link href="css/menu.css" type="text/css" rel="stylesheet" />
    <script type="text/javascript" language="javascript" src="js/global.js"></script>
    <script type="text/javascript" language="javascript" src="js/utils.js"></script>
    <script type="text/javascript" language="javascript" src="js/transport.js"></script>
    <script language="JavaScript" type="text/javascript">
<!--
var noHelp   = "<p align='center' style='color: #666'>There's no content.</p>";
var helpLang = "en";
var adminId = 1;
//-->
    </script>
</head><body>
        <div id="tabbar-div">
            <p>
                <span style="float: right; padding: 3px 5px;"><a href="javascript:toggleCollapse();">
                    <img id="toggleImg" src="images/menu_minus.gif" width="9" height="9" style="border: none 0px white;"
                        alt="collapse" /></a></span><span class="tab-front" id="menu-tab">Menu</span><span
                            class="tab-back" id="help-tab">Help</span></p>
        </div>
        <div id="main-div">
            <div id="menu-list">
                <ul>
                    <li class="explode" key="0" name="menu">Shortcut
                        <ul>
                            <li class="menu-item"><a href="cronlist" target="main-frame">Cron Job List</a></li>
                            <li class="menu-item"><a href="createcron" target="main-frame">Create Cron Job</a></li>
                            <li class="menu-item"><a href="loglist" target="main-frame">Run Log</a></li>
                        </ul>
                    </li>
                </ul>
            </div>
            <div id="help-div" style="display: none">
                <h1 id="help-title">
                </h1>
                <div id="help-content">
                </div>
            </div>
        </div>
    <script type="text/javascript" language="javascript">
<!--
var collapse_all = "collapse";
var expand_all = "expand";
var collapse = true;
function toggleCollapse()
{
  var items = document.getElementsByTagName('LI');
  for (i = 0; i < items.length; i++)
  {
    if (collapse)
    {
      if (items[i].className == "explode")
      {
        toggleCollapseExpand(items[i], "collapse");
      }
    }
    else
    {
      if ( items[i].className == "collapse")
      {
        toggleCollapseExpand(items[i], "explode");
        ToggleHanlder.Reset();
      }
    }
  }

  collapse = !collapse;
  document.getElementById('toggleImg').src = collapse ? 'images/menu_minus.gif' : 'images/menu_plus.gif';
  document.getElementById('toggleImg').alt = collapse ? collapse_all : expand_all;
}

function toggleCollapseExpand(obj, status)
{
  if (obj.tagName.toLowerCase() == 'li' && obj.className != 'menu-item')
  {
    for (i = 0; i < obj.childNodes.length; i++)
    {
      if (obj.childNodes[i].tagName == "UL")
      {
        if (status == null)
        {
          if (obj.childNodes[1].style.display != "none")
          {
            obj.childNodes[1].style.display = "none";
            ToggleHanlder.RecordState(obj.getAttribute("key"), "collapse");
            obj.className = "collapse";
          }
          else
          {
            obj.childNodes[1].style.display = "block";
            ToggleHanlder.RecordState(obj.getAttribute("key"), "explode");
            obj.className = "explode";
          }
          break;
        }
        else
        {
          if( status == "collapse")
          {
            ToggleHanlder.RecordState(obj.getAttribute("key"), "collapse");
            obj.className = "collapse";
          }
          else
          {
            ToggleHanlder.RecordState(obj.getAttribute("key"), "explode");
            obj.className = "explode";
          }
          obj.childNodes[1].style.display = (status == "explode") ? "block" : "none";
        }
      }
    }
  }
}
document.getElementById('menu-list').onclick = function(e)
{
  var obj = Utils.srcElement(e);
  toggleCollapseExpand(obj);
}

document.getElementById('tabbar-div').onmouseover = function(e)
{
  var obj = Utils.srcElement(e);

  if (obj.className == "tab-back")
  {
    obj.className = "tab-hover";
  }
}

document.getElementById('tabbar-div').onmouseout=function(e)
{
  var obj = Utils.srcElement(e);

  if (obj.className == "tab-hover")
  {
    obj.className = "tab-back";
  }
}

document.getElementById('tabbar-div').onclick=function(e)
{
  var obj = Utils.srcElement(e);

  var mnuTab = document.getElementById('menu-tab');
  var hlpTab = document.getElementById('help-tab');
  var mnuDiv = document.getElementById('menu-list');
  var hlpDiv = document.getElementById('help-div');

  if (obj.id == 'menu-tab')
  {
    mnuTab.className = 'tab-front';
    hlpTab.className = 'tab-back';
    mnuDiv.style.display = "block";
    hlpDiv.style.display = "none";
  }

  if (obj.id == 'help-tab')
  {
    mnuTab.className = 'tab-back';
    hlpTab.className = 'tab-front';
    mnuDiv.style.display = "none";
    hlpDiv.style.display = "block";

    loc = parent.frames['main-frame'].location.href;
    pos1 = loc.lastIndexOf("/");
    pos2 = loc.lastIndexOf("?");
    pos3 = loc.indexOf("act=");
    pos4 = loc.indexOf("&", pos3);

    filename = pos2 > 5 ? loc.substring(pos1 + 1, pos2 - 5) : loc.substring(pos1 + 1);
    if (pos3 >= 0)
    {
        act = pos4 < 0 ? loc.substring(pos3 + 4) : loc.substring(pos3 + 4, pos4);
    }
    else
    {
        act = "";
    }
    loadHelp(filename, act);
  }
}

/**
 * Load Help
 */
function loadHelp(filename, act)
{
  var doc = createDocument();
  var path = 'help/' + helpLang + '/' + filename + ".xml";

  document.getElementById("help-title").innerHTML = '';
  document.getElementById("help-content").innerHTML = noHelp;
  try
  {
    doc.load(path);

    var items = doc.getElementsByTagName('section');

    for (i = 0; i < items.length; i++)
    {
      if (act == "" || items[i].getAttribute("id") == act)
      {
        var title = items[i].getElementsByTagName("title");
        document.getElementById("help-title").innerHTML = (Browser.isIE) ? title[0].text : title[0].textContent;

        var content = items[i].getElementsByTagName("content");
        document.getElementById("help-content").innerHTML = (Browser.isIE) ? content[0].text : content[0].textContent;

        break;
      };
    }
  }
  catch (e)
  {
    //alert(e.message);
  }
}

/**
 * Create XML object
 */
function createDocument()
{
  var xmlDoc;

  // create a DOM object
  if (window.ActiveXObject)
  {
    try
    {
      xmlDoc = new ActiveXObject("Msxml2.DOMDocument.6.0");
    }
    catch (e)
    {
      try
      {
        xmlDoc = new ActiveXObject("Msxml2.DOMDocument.5.0");
      }
      catch (e)
      {
        try
        {
          xmlDoc = new ActiveXObject("Msxml2.DOMDocument.4.0");
        }
        catch (e)
        {
          try
          {
            xmlDoc = new ActiveXObject("Msxml2.DOMDocument.3.0");
          }
          catch (e)
          {
            alert(e.message);
          }
        }
      }
    }
  }
  else
  {
    if (document.implementation && document.implementation.createDocument)
    {
      xmlDoc = document.implementation.createDocument("","doc",null);
    }
    else
    {
      alert("Create XML object is failed.");
    }
  }
  xmlDoc.async = false;

  return xmlDoc;
}
//菜单展合状态处理器
var ToggleHanlder = new Object();
Object.extend(ToggleHanlder ,{
  SourceObject : new Object(),
  CookieName   : 'Toggle_State',
  RecordState : function(name,state)
  {
    if(state == "collapse")
    {
      this.SourceObject[name] = state;
    }
    else
    {
      if(this.SourceObject[name])
      {
        delete(this.SourceObject[name]);
      }
    }
    var date = new Date();
    date.setTime(date.getTime() + 99999999);
    document.setCookie(this.CookieName, this.SourceObject.toJSONString(), date.toGMTString());
  },

  Reset :function()
  {
    var date = new Date();
    date.setTime(date.getTime() + 99999999);
    document.setCookie(this.CookieName, "{}" , date.toGMTString());
  },

  Load : function()
  {
    if (document.getCookie(this.CookieName) != null)
    {
      this.SourceObject = eval("("+ document.getCookie(this.CookieName) +")");
      var items = document.getElementsByTagName('LI');
      for (var i = 0; i < items.length; i++)
      {
        if ( items[0].getAttribute("name") == "menu")
        {
          for (var k in this.SourceObject)
          {
            if ( typeof(items[i]) == "object")
            {
              if (items[i].getAttribute('key') == k)
              {
                toggleCollapseExpand(items[i], this.SourceObject[k]);
                collapse = false;
              }
            }
          }
        }
     }
    }
    document.getElementById('toggleImg').src = collapse ? 'images/menu_minus.gif' : 'images/menu_plus.gif';
    document.getElementById('toggleImg').alt = collapse ? collapse_all : expand_all;
  }
});
ToggleHanlder.CookieName += "_" + adminId;
//初始化菜单状态
ToggleHanlder.Load();
//-->
</script>
</body>
</html>""")
			else:
				self.response.headers['Content-Type'] = 'text/html'
				self.response.out.write("""
					<html>
					<head>
						<title>Menu - Beikx Cron</title>
						<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
					</head>
					<body>
						<div>
						You are no permission.
						</div>
					</body>
					</html>""")
		else:
			self.redirect(users.create_login_url(self.request.uri))

def main():
	application = webapp.WSGIApplication([('/left', LeftHandler)],
		debug=True)
	util.run_wsgi_app(application)


if __name__ == '__main__':
	main()
